/*
 *	This file is part of Lounge-Cast.
 *
 *  Author:  	Markus Moormann
 *	E-mail:  	mmoorman@uni-osnabrueck.de
 *	Copyright:	University of Osnabrueck (Zentrum Virtuos)
 * 	Website:	www.uni-osnabrueck.de
 *	Date:		16.02.2011
 *
 *	Lounge-Cast is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *	Lounge-Cast is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Lounge-Cast.  If not, see <http://www.gnu.org/licenses/>.
 */
package backend.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

import backend.dbConnection.ConnectionHelper;

/**
 * class for contact service
 *
 * @author Markus Moormann
 */
public class ContactService {
	
	/**
	 * a logger to log errors, debug information, etc.
	 */
	private static Logger LOG = Logger.getLogger(ContactService.class);
	/**
	 * the connection to database
	 */
	private Connection connection;
	/**
	 * the statement so send to database
	 */
	private Statement statement;

	/**
	 * send an email to a user
	 * 
	 * @param subject subject of email
	 * @param message message of mail
	 * @param sender sender of mail
	 * @param recipient recipient mail
	 * @return <code>true</code> on success, <code>false</code> else
	 */
	public boolean sendMailToUser(String subject, String message,
			String sender, String recipient) {

		try {
			connection = ConnectionHelper.getConnection();
			statement = connection.createStatement();
			
			SimpleEmail email = new SimpleEmail();
			//email.setDebug(true);
			email.setHostName("smtp.serv.uni-osnabrueck.de");
			
			String getEmail = 	"SELECT " +
									"user_name," +
									"user_email " +
								"FROM " +
									"user " +
								"WHERE " +
									"user_name IN ('" + sender + "','" + recipient + "')";
			
			ResultSet rs = statement.executeQuery(getEmail);
			while(rs.next()) {
				if(rs.getString("user_name").equals(sender)) {
					email.setFrom(rs.getString("user_email"), sender);
				}else {
					email.addTo(rs.getString("user_email"), recipient);
				}
			}
			email.setSubject(subject);
			email.setMsg(message);
			email.send();
			return true;
		} catch (EmailException e) {
			LOG.error(e);
		} catch (SQLException e) {
			LOG.error(e);
		}

		return false;
	}

}
